import re

import requests
from PySide6.QtUiTools import QUiLoader  # 动态加载ui文件

from PySide6.QtWidgets import QGraphicsScene, QApplication, QLabel
from bs4 import BeautifulSoup
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
import math
import pandas as pd
import numpy as np
import datetime
import weather


class MyFigureCanvas(FigureCanvas):
    """
    通过继承FigureCanvas类，使得该类既是一个Pyside的Qwidget，又是一个matplotlib的FigureCanvas，这是连接pyqt5与matplotlib的关键
    """

    def __init__(self, parent=None):
        self.figure = plt.Figure(tight_layout=True)  # tight_layout: 用于去除画图时两边的空白
        FigureCanvas.__init__(self, self.figure)  # 初始化父类
        self.setParent(parent)

        self.fig1 = self.figure.add_subplot(2, 2, 1)  # 添加子图 #两行两列第一个
        self.fig2 = self.figure.add_subplot(2, 2, 2)  # 添加子图函数，三个参数分别表示纵向分几个子图，横向分几个子图，当前为第几个子图
        self.fig3 = self.figure.add_subplot(2, 2, 3)
        self.fig4 = self.figure.add_subplot(2, 2, 4, projection='polar')


class MainWindow:

    def __init__(self):
        self.ui = QUiLoader().load('ui_code/MainWindow.ui')
        self.gv_visual_data_content = MyFigureCanvas()

        weather.main()
        self.main()
        url = 'http://www.weather.com.cn/weather15d/101180101.shtml'
        self.today_weather(url)

    def wether_show(self, data):
        data_today = datetime.date.today()
        data_tomorrow = data_today + datetime.timedelta(days=1)

        wea_today = data['天气'][0]
        wea_tomorrow = data['天气'][1]

        temlow_today = data['最低气温'][0]
        temlow_tomorrow = data['最低气温'][1]

        temhigh_today = data['最高气温'][0]
        temhigh_tomorrow = data['最高气温'][1]

        wind1_today = data['风向1'][0]
        wind1_tomorrow = data['风向1'][1]

        wind2_today = data['风向2'][0]
        wind2_tomorrow = data['风向2'][1]

        windgrade_today = data['风级'][0]
        windgrade_tomorrow = data['风级'][1]
        text1 = '郑州' + "  " + str(data_today) + "  " + str(wea_today) + "  " + str(temlow_today) + '~' + str(
            temhigh_today) + "℃  " \
                             '风向1：' + str(wind1_today) + "  " + '风向2：' + str(wind2_today) + "  " + '风级：' + str(
            windgrade_today)
        text2 = '郑州' + "  " + str(data_tomorrow) + "  " + str(wea_tomorrow) + "  " + str(temlow_tomorrow) + '~' + str(
            temhigh_tomorrow) + "℃  " \
                                '风向1：' + str(wind1_tomorrow) + "  " + '风向2：' + str(wind2_tomorrow) + "  " + '风级：' + str(
            windgrade_tomorrow)
        self.ui.label_1.setText(text1)
        self.ui.label_2.setText(text2)

    def today_weather(self, url):
        url = url
        req = requests.get(url)
        req.encoding = 'utf-8'
        soup = BeautifulSoup(req.text, 'lxml')
        description = soup.find('input', id='hidden_title')
        description = re.search(r'value="(.*)"', str(description))
        print(description.group(1))
        return description.group(1)

    def tem_pic(self, data):
        # 温度曲线
        Xplot_title = '时间/h'
        Yplot_title = '摄氏度/℃'
        Plot_title = '一天温度变化曲线图'
        hour = list(data['小时'])
        tem = list(data['温度'])
        for i in range(0, 24):
            if math.isnan(tem[i]) == True:
                tem[i] = tem[i - 1]
        tem_ave = sum(tem) / 24  # 求平均温度
        tem_max = max(tem)
        tem_max_hour = hour[tem.index(tem_max)]  # 求最高温度
        tem_min = min(tem)
        tem_min_hour = hour[tem.index(tem_min)]  # 求最低温度
        x = []
        y = []
        for i in range(0, 24):
            x.append(i)
            y.append(tem[hour.index(i)])

        self.gv_visual_data_content.fig1.plot(x, y, color='red', label='温度')
        self.gv_visual_data_content.fig1.scatter(x, y, color='red', linewidths=0.1)  # 点出每个时刻的温度点
        self.gv_visual_data_content.fig1.plot([0, 24], [tem_ave, tem_ave], c='blue', linestyle='--', label='平均温度')
        self.gv_visual_data_content.fig1.set_xlabel(Xplot_title, fontsize=12)
        self.gv_visual_data_content.fig1.set_ylabel(Yplot_title, fontsize=12)
        self.gv_visual_data_content.fig1.set_title(Plot_title, fontsize=12)  # 标题
        self.gv_visual_data_content.fig1.legend()  # 显示线条信息

    def humidity_pic(self, data):
        # 相对湿度曲线
        Xplot_title = '时间/h'
        Yplot_title = '百分比/%'
        Plot_title = '一天相对湿度变化曲线图'
        hour = list(data['小时'])
        hum = list(data['相对湿度'])
        for i in range(0, 24):
            if math.isnan(hum[i]) == True:
                hum[i] = hum[i - 1]
        hum_ave = sum(hum) / 24  # 求平均相对湿度
        hum_max = max(hum)
        hum_max_hour = hour[hum.index(hum_max)]  # 求最高相对湿度
        hum_min = min(hum)
        hum_min_hour = hour[hum.index(hum_min)]  # 求最低相对湿度
        x = []
        y = []
        for i in range(0, 24):
            x.append(i)
            y.append(hum[hour.index(i)])
        self.gv_visual_data_content.fig2.plot(x, y, color='blue', label='相对湿度')
        self.gv_visual_data_content.fig2.plot([0, 24], [hum_ave, hum_ave], c='red', linestyle='--', label='平均相对湿度')
        self.gv_visual_data_content.fig2.scatter(x, y, color='blue', linewidths=0.1)
        self.gv_visual_data_content.fig2.set_xlabel(Xplot_title, fontsize=12)
        self.gv_visual_data_content.fig2.set_ylabel(Yplot_title, fontsize=12)
        self.gv_visual_data_content.fig2.set_title(Plot_title, fontsize=12)  # 标题
        self.gv_visual_data_content.fig2.legend()

    def air_pic(self, data):
        # 空气质量
        Xplot_title = '时间/h'
        Yplot_title = '空气质量指数AQI'
        Plot_title = '一天空气质量变化曲线图'
        hour = list(data['小时'])
        air = list(data['空气质量'])

        for i in range(0, 24):
            if math.isnan(air[i]) == True:
                air[i] = air[i - 1]
        air_ave = sum(air) / 24  # 求平均空气质量
        air_max = max(air)
        air_max_hour = hour[air.index(air_max)]  # 求最高空气质量
        air_min = min(air)
        air_min_hour = hour[air.index(air_min)]  # 求最低空气质量
        x = []
        y = []
        for i in range(0, 24):
            x.append(i)
            y.append(air[hour.index(i)])

        for i in range(0, 24):
            if y[i] <= 50:
                self.gv_visual_data_content.fig3.bar(x[i], y[i], color='lightgreen', width=0.7)  # 1等级
            elif y[i] <= 100:
                self.gv_visual_data_content.fig3.bar(x[i], y[i], color='wheat', width=0.7)  # 2等级
            elif y[i] <= 150:
                self.gv_visual_data_content.fig3.bar(x[i], y[i], color='orange', width=0.7)  # 3等级
            elif y[i] <= 200:
                self.gv_visual_data_content.fig3.bar(x[i], y[i], color='orangered', width=0.7)  # 4等级
            elif y[i] <= 300:
                self.gv_visual_data_content.fig3.bar(x[i], y[i], color='darkviolet', width=0.7)  # 5等级
            elif y[i] > 300:
                self.gv_visual_data_content.fig3.bar(x[i], y[i], color='maroon', width=0.7)  # 6等级
        self.gv_visual_data_content.fig3.plot([0, 24], [air_ave, air_ave], c='black', linestyle='--')
        self.gv_visual_data_content.fig3.set_xlabel(Xplot_title, fontsize=12)
        self.gv_visual_data_content.fig3.set_ylabel(Yplot_title, fontsize=12)
        self.gv_visual_data_content.fig3.set_title(Plot_title, fontsize=12)  # 标题

    def wind_pic(self, data):
        # 风向雷达图
        Plot_title = '一天风级图'
        wind = list(data['风力方向'])
        wind_speed = list(data['风级'])
        for i in range(0, 24):
            if wind[i] == "北风":
                wind[i] = 90
            elif wind[i] == "南风":
                wind[i] = 270
            elif wind[i] == "西风":
                wind[i] = 180
            elif wind[i] == "东风":
                wind[i] = 360
            elif wind[i] == "东北风":
                wind[i] = 45
            elif wind[i] == "西北风":
                wind[i] = 135
            elif wind[i] == "西南风":
                wind[i] = 225
            elif wind[i] == "东南风":
                wind[i] = 315
        degs = np.arange(45, 361, 45)
        temp = []
        for deg in degs:
            speed = []
            # 获取 wind_deg 在指定范围的风速平均值数据
            for i in range(0, 24):
                if wind[i] == deg:
                    speed.append(wind_speed[i])
            if len(speed) == 0:
                temp.append(0)
            else:
                temp.append(sum(speed) / len(speed))
        # print(temp)
        N = 8
        theta = np.arange(0. + np.pi / 8, 2 * np.pi + np.pi / 8, 2 * np.pi / 8)
        # 数据极径
        radii = np.array(temp)
        # self.gv_visual_data_content.fig4.axes(polar=True)
        # 定义每个扇区的RGB值（R,G,B），x越大，对应的颜色越接近蓝色
        colors = [(1 - x / max(temp), 1 - x / max(temp), 0.6) for x in radii]
        self.gv_visual_data_content.fig4.bar(theta, radii, width=(2 * np.pi / N), bottom=0.0, color=colors)
        self.gv_visual_data_content.fig4.set_title(Plot_title, fontsize=12)  # 标题

    def main(self):  # 最后一个图层时展示即可
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        data1 = pd.read_csv('weather1.csv', encoding='gb2312')
        data2 = pd.read_csv('weather14.csv', encoding='gb2312', nrows=2)
        self.tem_pic(data1)
        self.humidity_pic(data1)
        self.air_pic(data1)
        self.wind_pic(data1)
        self.wether_show(data2)

        self.graphic_scene = QGraphicsScene()
        self.graphic_scene.addWidget(self.gv_visual_data_content)
        self.ui.graphicsView_1.setScene(self.graphic_scene)  # 把QGraphicsScene放入QGraphicsView
        self.ui.graphicsView_1.show()


if __name__ == "__main__":
    app = QApplication([])
    # 实例化窗口
    mainwindow = MainWindow()
    mainwindow.ui.show()
    app.exec()
